package so.sao.code.service.infrastructure.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.tuple.Pair;

/**
 * 码段信息工具类
 * 
 * @author cuijunhua
 *
 */
public class RangeUtil {

	/**
	 * 将一个连续的码段分成N段，不能平分时，最后一段缺省
	 * 
	 * @param seqnumStart
	 * @param seqnumEnd
	 * @param count
	 * @return
	 */
	public static List<Pair<Long, Long>> rangeSplit(long seqnumStart, long seqnumEnd, int count) {

		long tagCount = seqnumEnd - seqnumStart + 1;
		List<Pair<Long, Long>> ranges = new ArrayList<>();
		long segment = 0;
		if (tagCount % count == 0) {
			segment = tagCount / count;
			for (int i = 0; i < count; i++) {
				ranges.add(Pair.of(seqnumStart, seqnumStart + segment - 1));
				seqnumStart += segment;
			}
		} else {
			segment = (tagCount - tagCount % count) / count;
			long remainder = tagCount % count;
			for (int i = 0; i < count; i++) {
				if (i < remainder) {
					ranges.add(Pair.of(seqnumStart, seqnumStart + segment));
					seqnumStart += segment + 1;
				} else {
					ranges.add(Pair.of(seqnumStart, seqnumStart + segment - 1));
					seqnumStart += segment;
				}
			}
		}

		return ranges;
	}
}
